package com.kenyi.co.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 检测网络的联通情况
 */

public class ConnectNet {
	private static Context content;

	/**
	 * 检查网络的连通性
	 * 
	 * @return
	 */
	public static boolean isNetworkReachable(Context content) {

		final ConnectivityManager mManger = (ConnectivityManager) content
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo current = mManger.getActiveNetworkInfo();
		if (current == null) {
			return false;
		}
		return (current.getState() == NetworkInfo.State.CONNECTED);
	}

	public static boolean hasNetworkConnectect(Context content) {
		final ConnectivityManager mManger = (ConnectivityManager) content
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		final NetworkInfo activeNetworkInfo = mManger.getActiveNetworkInfo();
		// 如果没有网络
		Boolean connected = (null != activeNetworkInfo) && activeNetworkInfo.isConnected();
		if (!connected)
			return false;
		// 检查是否可以访问远程服务器
		boolean routeExists;
		try {
			InetAddress host = InetAddress.getByName("8.8.8.8");
			Socket s = new Socket();
			s.connect(new InetSocketAddress(host, 53), 5000);
			routeExists = true;
			s.close();

		} catch (Exception e) {
			routeExists = false;
		}
		return (connected && routeExists);
	}
	public static boolean isWifiReachable(Context content){
		final ConnectivityManager mManger = (ConnectivityManager) content
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo current = mManger.getActiveNetworkInfo();
		if (current == null) {
			return false;

		}
		return (current.getType() == ConnectivityManager.TYPE_WIFI);
	}
}
